import json
from datetime import time, datetime

from django.contrib.auth.models import User
from django.contrib import auth
from django.shortcuts import redirect, render, HttpResponse
from django.urls import reverse

from . import models
from .form import register_form, login_form


def index(request):
    return render(request, 'index.html')


def logout(request):
    # TODO finish the session
    request.session.flush()
    logout = auth.logout(request)
    return redirect(reverse('login'))


def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        infoJson = json.loads(request.read())
        userName = infoJson['username']
        passWord = infoJson['password']
        userObj = auth.authenticate(username=userName, password=passWord)
        if not userObj:
            return HttpResponse(jsonResponse(500, '密码错误', None).getJson())
        else:  # login success
            auth.login(request, userObj)
            # TODO finish the return and session
            request.session['islogin'] = True
            request.session['username'] = userName
            # csrftoken = request.COOKIES.get('X-CSRFToken')
            # res = redirect(reverse('index')).set_cookie('X-CSRFToken', csrftoken)
            return HttpResponse(jsonResponse(0, '', None).getJson())


def registered(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    else:
        infoJson = json.loads(request.read())
        userName = infoJson['username']
        passWord = infoJson['password']
        email = infoJson['email']
        userobj = models.AuthUser.objects.filter(username=userName).first()
        if userobj:
            return HttpResponse(jsonResponse(500, '用户名已经存在', None).getJson())
        User.objects.create_user(username=userName, password=passWord, email=email)
        return HttpResponse(jsonResponse(0, '', None).getJson())


def userInfo(request):
    isLogin = request.session.get('islogin')
    if not isLogin:
        res = jsonResponse(500, 'Need to login', None)
        return HttpResponse(res.getJson())
    userName = request.session.get('username')
    user = models.AuthUser.objects.get(username=userName)
    userdata = dict()
    userdata['username'] = user.username
    userdata['lastlogin'] = user.last_login
    userdata['datejoined'] = user.date_joined
    return HttpResponse(jsonResponse(0, '', userdata).getJson())


class jsonResponse():
    def __init__(self, status, msg, data):
        self.status = status
        self.msg = msg
        self.data = data

    def __int__(self, status, msg, dataDic):
        self.status = status
        self.msg = msg
        self.data = dataDic

    def getJson(self):
        dicRes = dict()
        dicRes['status'] = self.status
        dicRes['msg'] = self.msg
        dicRes['data'] = self.data
        return json.dumps(dicRes, cls=DateEncoder)

    def makeDicAndGetJson(self):
        dicRes = dict()
        dicRes['status'] = self.status
        dicRes['msg'] = self.msg
        dic = dict()
        dic['rows'] = self.data
        dicRes['data'] = dic
        return json.dumps(dicRes, cls=DateEncoder)


class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime("%Y-%m-%d")
        else:
            return json.JSONEncoder.default(self, obj)


class Checker():
    def __init__(self, jsonStr):
        self.jsonStr = jsonStr

    def checkandgetjson(self):
        try:
            requestInfo = json.loads(self.jsonStr)
        except Exception:
            return False
        return requestInfo
